/*
 * @LastEditors: YuSeen 2290515673@qq.com
 * @LastEditTime: 2022-08-21 15:44:35
 * 天凉好个秋
 */
import { storage } from "@/types/localStorage/index";

export const useLocalStorage = () => {
  // 读取本地存储中的某项数据
  const getStorageItem = <T = any>(key: string) => {
    const res = localStorage.getItem(key)
    if(res === null) return undefined
    try {
      return JSON.parse(res) as unknown as T;
    } catch (error) {
      return res as unknown as T;
    }
  };
  // 设置本地存储中的某项数据
  const setStorageItem = (key: string, value: any) => {
    if (typeof value === "object")
      return localStorage.setItem(key, JSON.stringify(value));
    localStorage.setItem(key, value);
  };
  //   移除本地存储中的某项数据
  const removeStorageItem = (key: string) => {
    localStorage.removeItem(key);
  };

  // 读取历史搜索记录
  const getHistorySearch = (): storage["historySearch"] => {
    const data = getStorageItem("historySearch");
    if (data !== null && data !== undefined) return data;
    return [];
  };

  //   添加搜索历史记录,最多存储20条
  const addHistorySearch = (keyword: string) => {
    let list = new Set(getHistorySearch());
    if (list.has(keyword)) list.delete(keyword);
    const result = [keyword, ...list];
    if (result.length >= 20) result.pop();
    setStorageItem("historySearch", result);
  };
  //   删除某项搜索记录
  const removeHistorySearch = (keyword: string) => {
    const list = getHistorySearch();
    const index = list.indexOf(keyword);
    list.splice(index, 1);
    setStorageItem("historySearch", list);
  };
  // 清除所有搜索历史记录
  const clearHistorySearch = () => {
    removeStorageItem("historySearch");
  };

  return {
    getStorageItem,
    setStorageItem,
    getHistorySearch,
    addHistorySearch,
    removeHistorySearch,
    clearHistorySearch
  };
};
